<template>
    <div>
        <!--搜索表单-->
        <div>
            <Form ref="search" :model="search" inline :label-width="60">
                <FormItem prop="userName" label="住户">
                    <Input type="text" v-model="search.userName" placeholder="住户">
                    </Input>
                </FormItem>
                <FormItem prop="passResult" label="健康状态">
                    <Select v-model="search.healthStatus" style="width: 180px">
                        <i-option value="0">健康</i-option>
                        <i-option value="1">异常</i-option>
                        <i-option value="2">确诊</i-option>
                    </Select>
                </FormItem>
                <DatePicker v-model="search.dates" format="yyyy/MM/dd" type="daterange" placement="bottom-end"
                            placeholder="选择入档日期范围" style="width: 200px;margin-left: 40px;"></DatePicker>
                <FormItem prop="field" label="排序项">
                    <Select v-model="search.field" style="width: 180px">
                        <i-option value="statusId">编号</i-option>
                        <i-option value="userId">住户</i-option>
                        <i-option value="temperature">体温</i-option>
                        <i-option value="accessTimes">出入次数</i-option>
                        <i-option value="updateTime">更新时间</i-option>
                    </Select>
                </FormItem>
                <FormItem prop="isAsc" label="排序">
                    <Select v-model="search.isAsc" style="width: 180px">
                        <i-option :value="1">正序</i-option>
                        <i-option :value="0">倒序</i-option>
                    </Select>
                </FormItem>
            </Form>
        </div>
        <!--表头操作按钮-->
        <div class="mb20">
            <Button type="primary" icon="ios-add-circle-outline" @click="showAddModal">添加</Button>
<!--            <Button type="error" :disabled="del_disabled" icon="md-trash" @click="deleteList" class="ml20">删除</Button>-->
<!--            <Button type="warning" icon="ios-cloud-upload-outline" @click="" class="ml20">导入</Button>-->
            <Button type="success" icon="ios-cloud-download-outline" @click="exportExcel" class="ml20">导出</Button>
            <Button type="warning" icon="ios-notifications-outline" @click="showMessageModal" class="ml20">发送消息</Button>
            <Button type="primary" icon="ios-search" @click="searchSubmit" class="ml20">搜索</Button>
            <Button icon="md-refresh" @click="handleReset" class="ml20">Reset</Button>
        </div>
        <Table border stripe :columns="columns" :data="data" :loading="loading"
               @on-select="on_select" @on-select-cancel="on_select_cancel"
               @on-select-all="on_select_all" @on-select-all-cancel="on_select_all_cancel">
            <!--使用插槽处理自定义渲染的数据-->
            <template slot-scope="{ row, index }" slot="userName">
                <span>{{row.sysUser.name}}</span>
            </template>
            <template slot-scope="{ row, index }" slot="healthStatus">
                <Tag color="success" v-if="row.healthStatus===0">{{row.healthStatusMeaning}}</Tag>
                <Tag color="warning" v-else-if="row.healthStatus===1">{{row.healthStatusMeaning}}</Tag>
                <Tag color="error" v-else>{{row.healthStatusMeaning}}</Tag>
            </template>

            <template slot-scope="{ row, index }" slot="change">
                <Button @click="statusChange(row.userId)" shape="circle"><Icon size="20" type="ios-eye" /></Button>
            </template>
            <template slot-scope="{ row, index }" slot="action">
                <Button type="info" icon="md-create" size="small" @click="showChangeModal(row)"
                        style="margin-top: 5px;">修改
                </Button>
            </template>
        </Table>
        <Page :total="pageData.totalElements" :page-size="pageSize" show-elevator show-total @on-change="change"
              class-name="page-style"></Page>
        <!--状态变化弹窗-->
        <el-dialog title="体温变化折线图" :visible.sync="modal_statusChange" width="35%">
            <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
            <body-chart :chart-data="bodyChartData" />
          </el-row>
        </el-dialog>

        <!--添加弹窗-->
        <Modal :closable=false
               title="新增住户健康状态"
               v-model="modal_add"
               ok-text="确定"
               @on-ok="handleSubmit('formAdd',formAdd)"
               class-name="vertical-center-modal">
            <div>
                <Form ref="formAdd" :model="formAdd" :rules="ruleInline">
                    <FormItem prop="userId" label="住户">
                        <Select filterable  v-model="formAdd.userId" style="width: 200px">
                            <i-option v-for="item in allUser" :key="item.userId"
                                      :value="item.userId">{{item.name}}</i-option>
                        </Select>
                    </FormItem>
                    <FormItem prop="temperature" label="体温">
                        <Input type="text" v-model="formAdd.temperature" placeholder="请输入体温"></Input>
                    </FormItem>
                    <FormItem prop="passResult" label="健康状态">
                        <Select v-model="formAdd.healthStatus" style="width: 200px">
                            <i-option value="0">健康</i-option>
                            <i-option value="1">异常</i-option>
                            <i-option value="2">确诊</i-option>
                        </Select>
                    </FormItem>
                    <FormItem prop="accessTimes" label="出入次数">
                        <Input type="text" v-model="formAdd.accessTimes" placeholder="请输入出入次数"></Input>
                    </FormItem>
                    <FormItem prop="remarks" label="备注">
                        <Input type="textarea" v-model="formAdd.remarks" placeholder="请输入备注"></Input>
                    </FormItem>
                </Form>
            </div>
        </Modal>
        <!--修改弹窗-->
        <Modal :closable=false
               title="修改住户信息"
               v-model="modal_change"
               ok-text="确定"
               @on-ok="handleSubmit('formChange',formChange)">
            <div>
                <Form ref="formChange" :model="formChange" :rules="ruleInline">
                    <FormItem prop="temperature" label="体温">
                        <Input type="text" v-model="formChange.temperature" placeholder="请输入体温"></Input>
                    </FormItem>
                    <FormItem prop="passResult" label="健康状态">
                        <Select v-model="formChange.healthStatus" style="width: 200px">
                            <i-option value="0">健康</i-option>
                            <i-option value="1">异常</i-option>
                            <i-option value="2">确诊</i-option>
                        </Select>
                    </FormItem>
                    <FormItem prop="accessTimes" label="出入次数">
                        <Input type="text" v-model="formChange.accessTimes" placeholder="请输入出入次数"></Input>
                    </FormItem>
                    <FormItem prop="remarks" label="备注">
                        <Input type="textarea" v-model="formChange.remarks" placeholder="请输入备注"></Input>
                    </FormItem>
                </Form>
            </div>
        </Modal>
        <!--发送提醒消息-->
        <Modal :closable=false
               title="发送提醒消息"
               v-model="modal_message"
               ok-text="确定"
               @on-ok="handleMessageSubmit()"
               class-name="vertical-center-modal">
            <div>
                <Alert show-icon class="mb20">
                    给住户发送提醒
                </Alert>
                <Form ref="formMessage" :model="formMessage" :rules="ruleInline">
                    <FormItem prop="title" label="消息标题">
                        <Input type="text" v-model="formMessage.title" placeholder="请输入消息标题"></Input>
                    </FormItem>
                    <FormItem prop="content" label="消息内容">
                        <Input type="textarea" v-model="formMessage.content" placeholder="请输入消息内容"></Input>
                    </FormItem>
                </Form>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {dateToString, downloadExcel, exportExcel} from "../utils/util";
    import BodyChart from './components/BodyChart'
    export default {
        name: "HealthStatus",
        data() {
            return {
                modal_statusChange:false,
                loading: false,  //是否显示表格加载
                modal_add: false,
                modal_change: false,
                modal_reset: false,
                modal_message: false,
                del_disabled: true,
                isSearch: false,   //当前是不是搜索模式
                data: [],
                current: 1,
                pageSize: 5,
                pageData: [],
                columns: [
                    {
                        type: 'selection',  //可以选择的一项
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '编号',
                        key: 'statusId',
                        sortable: true
                    },
                    {
                        title: '住户',
                        slot: 'userName'
                    },
                    {
                        title: '体温',
                        key: 'temperature'
                    },
                    {
                        title: '健康状态',
                        slot: 'healthStatus',
                        width: 90
                    },
                    {
                        title: '通行次数',
                        key: 'accessTimes'
                    },
                    {
                        title: '备注',
                        key: 'remarks'
                    },
                    {
                        title: '近况',
                        align: 'center',
                        slot: 'change',
                        width: 90
                    },
                    {
                        title: '更新时间',
                        key: 'updateTime'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 90
                    }
                ],
                formAdd: {
                    userId: null,
                    temperature: null,
                    healthStatus: null,
                    accessTimes: null,
                    remarks: null
                },
                formChange: {
                    statusId: null,
                    userId: null,
                    temperature: null,
                    healthStatus: null,
                    accessTimes: null,
                    remarks: null
                },
                formMessage: {
                  ids: [],
                  title: null,
                  content: null
                },
                ruleInline: {
                    userId: [
                        {required: true, message: '住户不能为空', trigger: 'blur',type:'number'}
                    ],
                    temperature: [
                        {required: true, message: '体温不能为空', trigger: 'blur'},
                        { type: 'string',pattern:/^(([1-9]\d{0,2})|0)(\.\d{0,2})?$/, message:'请输入两位小数的浮点数体温', trigger:'blur'}
                    ],
                    healthStatus: [
                        {required: true, message: '健康状态不能为空', trigger: 'blur'}
                    ],
                    accessTimes: [
                        {required: true, message: '出入次数不能为空', trigger: 'blur'},
                        { type: 'string',pattern:/^\d+$/, message:'请输入数字', trigger:'blur'}
                    ],
                    title: [
                        {required: true, message: '消息标题不能为空', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '消息内容不能为空', trigger: 'blur'}
                    ]
                },
                selectIds: [],     //表格中的选中项的Id
                search: {
                    userName: '',
                    healthStatus: null,
                    remarks: '',
                    dates: [],
                    page: 1,
                    size: 10,
                    isAsc: 1,
                    field: ''
                },
                allUser: [],
                bodyChartData: {
                expectedData: [1,2,3,4,5],
                    actualData: [34,35,36,37,38]
            },
            }
        },
        created() {
            this.query();
            this.getAllUser()
        },
    components: {
     BodyChart
    },
        methods: {
            statusChange(userId){
                let that=this
                this.request({
                    url: '/health/statusChange',
                    method: 'get',
                    params: {userId: userId},
                }).then(res=>{
                    console.log(userId)
                    that.bodyChartData.actualData=res.data.data
                    that.bodyChartData.expectedData=res.data.title
                })
                this.modal_statusChange=true
            },
            query() {
                this.loading = true  //显示表格加载动画
                this.request({
                    url: '/health/status',
                    method: 'get',
                    params: {page: this.current, size: this.pageSize}
                }).then(res => {
                    this.data = res.data.content
                    this.pageData = res.data
                }).finally(() => {
                    this.loading = false
                })
            },
            change(current) {
                this.current = current;
                this.refreshData();
            },
            refreshData() {
                //刷新数据
                //判断当前页面是不是搜索模式
                if (this.isSearch) {
                    this.querySearch();
                } else {
                    this.query();
                }
            },
            on_select(selection, row) {
                this.selectIds.push(row.statusId)
                this.formMessage.ids.push(row.userId)
                this.del_disabled = false //去掉删除按钮的禁用状态
            },
            on_select_cancel(selection, row) {
                this.selectIds.forEach((t, index, arr) => {
                    if (row.statusId === t) {
                        arr.splice(index, 1);    //删除取消的选项
                    }
                })
                if (this.selectIds.length === 0) {
                    this.del_disabled = true //删除按钮的禁用状态
                }
                this.formMessage.ids.forEach((t, index, arr) => {
                    if (row.userId === t) {
                        arr.splice(index, 1);    //删除取消的选项
                    }
                })
            },
            on_select_all(selection) {
                selection.forEach((t, index, arr) => {
                    this.selectIds.push(t.statusId)
                    this.formMessage.ids.push(t.userId)
                })
                this.del_disabled = false //去掉删除按钮的禁用状态
            },
            on_select_all_cancel(selection) {
                this.formMessage.ids = []
                this.selectIds = []
                this.del_disabled = true //删除按钮的禁用状态
            },
            deleteList() {
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                this.$Modal.confirm({
                    title: '提醒',
                    content: '确定要删除所选中的所有出入记录数据？',
                    onOk: () => {
                        this.loading = true
                        this.request({
                            url: '/health/status/list',
                            method: 'delete',
                            params: {ids: this.selectIds},
                            paramsSerializer: params => {
                                return this.$qs.stringify(params, {indices: false})
                            }
                        }).then(res => {
                            this.$Message.info(res.msg);
                            this.refreshData(); //更新当前页面
                        }).finally(() => {
                            this.loading = false
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('已取消删除');
                    }
                });
            },
            //重置按键
            handleReset() {
                this.search = {
                    userName: '',
                    healthStatus: null,
                    remarks: '',
                    dates: [],
                    page: 1,
                    size: 10,
                    isAsc: 1,
                    field: ''
                }
                //重置页面
                this.isSearch = false
                this.current = 1
                this.query()
            },
            searchSubmit() {
                //条件搜索
                this.current = 1
                this.isSearch = true
                this.querySearch();
            },
            querySearch() {
                this.loading = true
                let dates = this.search.dates
                if (dates.length < 2) {
                    this.search.dates = ['', '']
                }
                if (dates.length === 2) {
                    this.search.dates = [dateToString(dates[0]), dateToString(dates[1])]
                }
                this.search.page = this.current
                this.search.size = this.pageSize

                this.request({
                    url: '/health/status/search',
                    method: 'get',
                    params: this.search,
                    paramsSerializer: params => {
                        return this.$qs.stringify(params, {indices: false})
                    }
                }).then(res => {
                    this.data = res.data.content
                    this.pageData = res.data
                    // console.log(this.data)
                }).finally(() => {
                    this.loading = false
                })
            },
            showAddModal() {
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                this.modal_add = true;
                this.formAdd = {
                    userId: null,
                    temperature: null,
                    healthStatus: null,
                    accessTimes: null,
                    remarks: null
                }
            },
            showChangeModal(row) {
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                //展示弹窗
                this.modal_change = true
                //要修改的信息
                this.formChange.statusId = row.statusId
                this.formChange.userId = row.userId
                this.formChange.temperature = row.temperature + ''
                this.formChange.healthStatus = row.healthStatus + ''
                this.formChange.accessTimes = row.accessTimes + ''
                this.formChange.remarks = row.remarks
            },
            showMessageModal(){
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                if (this.formMessage.ids.length==0){
                    this.$Modal.confirm({
                        title: '提醒',
                        content: '确定要所有住户发送消息提醒？',
                        onOk: () => {
                            this.modal_message = true
                        },
                        onCancel: () => {
                            this.$Message.info('已取消');
                        }
                    });
                }else {
                    this.modal_message = true
                }
            },
            handleSubmit(name, data) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.request({
                            url: '/health/status',
                            method: 'post',
                            data: JSON.stringify(data),
                        }).then(res => {
                            this.refreshData();        //更新修改行的数据
                            this.$Message.success(res.msg);
                        }).finally(() => {
                            this.loading = false
                        })
                    } else {
                        this.$Message.error('填写内容不符合要求!');
                    }
                })
            },
            handleMessageSubmit() {
                this.$refs['formMessage'].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.request({
                            url: '/message/send/user/list',
                            method: 'post',
                            data: JSON.stringify(this.formMessage),
                        }).then(res => {
                            this.$Message.success(res.msg);
                            this.formMessage = {
                                ids: [],
                                title: null,
                                content: null
                            }
                        }).finally(() => {
                            this.loading = false
                        })
                    } else {
                        this.$Message.error('填写内容不符合要求!');
                    }
                })
            },
            getAllUser(){
                this.request({
                    url: '/user/all',
                    method: 'get'
                }).then(res => {
                    this.allUser =  res.data
                })
            },
            exportExcel(){
                exportExcel('/health/status/export/excel',this.selectIds)
            }
        }
    }
</script>

<style  scoped>

</style>